﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.SharePoint.WebPartPages;
using System.Web.UI.WebControls;
using NT.SharePoint.RS.ReportingServiceWS;
using System.Web.UI;
using NT.SharePoint.RS.WebParts;
using NT.SharePoint.RS.WebParts.BO;

namespace NT.SharePoint.RS.WebParts.ToolParts
{
    public class RSParametersToolPart : ToolPart
    {
        public RSParametersToolPart()
        {
            this.Title = "RS Report Parameters";
        }

        DataList parametersDL;
        LinkButton lb;

        public void ResfreshDisplay(string reportPath)
        {
            WPRSView wp = this.ParentToolPane.SelectedWebPart as WPRSView;

            Dictionary<string, RSParameter> parameters;
            parameters = wp.GetRSParameters(reportPath, false);

            parametersDL.DataSource = parameters.Values;
            parametersDL.DataBind();
        }

        protected override void CreateChildControls()
        {
            WPRSView wp = this.ParentToolPane.SelectedWebPart as WPRSView;


            Dictionary<string, RSParameter> parameters;
            parameters = wp.GetRSParameters(false);

            parametersDL = new DataList();
            parametersDL.ID = "parametersDL";
            parametersDL.ItemTemplate = new RSParametersTemplate(this.ParentToolPane.SelectedWebPart as WPRSView);
            parametersDL.DataSource = parameters.Values;
            parametersDL.DataBind();

            this.Controls.Add(parametersDL);

            Literal l = new Literal();
            l.Text = "<br>";
            this.Controls.Add(l);
        }

        private void RemoveConnectedParameters(Dictionary<string, ReportParameter> parameters)
        {
            WPRSView wp = this.ParentToolPane.SelectedWebPart as WPRSView;

            foreach (System.Web.UI.WebControls.WebParts.WebPartConnection connection in WebPartManager.Connections)
            {
                if (connection.ConsumerConnectionPointID == "IFilterValues" && connection.Transformer is TransformableFilterValuesToFilterValuesTransformer)
                {
                    string valueName = ((TransformableFilterValuesToFilterValuesTransformer)connection.Transformer).MappedConsumerParameterName;
                    if (parameters.ContainsKey(valueName))
                    {
                        parameters.Remove(valueName);
                    }
                }
            }
        }

        public override void ApplyChanges()
        {
            WPRSView wp = this.ParentToolPane.SelectedWebPart as WPRSView;

            UpdateRSWPParametersValues();
        }

        private void UpdateRSWPParametersValues()
        {
            WPRSView wp = this.ParentToolPane.SelectedWebPart as WPRSView;

            //Get DataList Control Data
            Dictionary<string, string> parameters = new Dictionary<string, string>();
            foreach (DataListItem item in this.parametersDL.Items)
            {
                string name = ((Literal)item.FindControl("Name")).Text;

                string value = "";
                TextBox tbValue = ((TextBox)item.FindControl("Value"));
                DropDownList ddlValue = ((DropDownList)item.FindControl("DDLValue"));
                CheckBoxList cblValue = ((CheckBoxList)item.FindControl("CBLValue"));

                if (tbValue.Visible)
                {
                    value = tbValue.Text;
                }
                else
                {
                    if (ddlValue.Visible)
                    {
                        value = ddlValue.SelectedValue;
                    }
                    else
                    {
                        int tmpCount = 0;
                        foreach (ListItem cbItem in cblValue.Items)
                        {
                            if (cbItem.Selected)
                            {
                                if (tmpCount > 0)
                                {
                                    value = string.Concat(value, ";");
                                }

                                value = string.Concat(value, cbItem.Value);

                                tmpCount++;
                            }
                        }
                    }
                }

                parameters.Add(name, value);
            }

            //Serialize the dictionnary content
            System.Runtime.Serialization.Formatters.Binary.BinaryFormatter ser = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
            System.IO.MemoryStream stream = new System.IO.MemoryStream();
            ser.Serialize(stream, parameters);
            wp.RSParameters = Convert.ToBase64String(stream.ToArray());

            wp.DataBind();
        }
    }

    class RSParametersTemplate : ITemplate
    {
        private WPRSView selectedWP;

        public RSParametersTemplate(WPRSView selectedWP)
        {
            this.selectedWP = selectedWP;
        }

        #region ITemplate Members

        public void InstantiateIn(Control container)
        {
            Literal l = new Literal();
            l.ID = "Name";
            l.Text = "Name";
            l.DataBinding += new EventHandler(Name_DataBinding);
            container.Controls.Add(l);

            l = new Literal();
            l.Text = ":<br>";
            container.Controls.Add(l);

            TextBox tb = new TextBox();
            tb.ID = "Value";
            tb.DataBinding += new EventHandler(Value_DataBinding);
            container.Controls.Add(tb);

            DropDownList ddList = new DropDownList();
            ddList.ID = "DDLValue";
            ddList.DataTextField = "Label";
            ddList.DataValueField = "Value";
            ddList.DataBinding += new EventHandler(ddList_DataBinding);
            container.Controls.Add(ddList);

            CheckBoxList cbList = new CheckBoxList();
            cbList.ID = "CBLValue";
            cbList.DataTextField = "Label";
            cbList.DataValueField = "Value";
            cbList.DataBinding += new EventHandler(cbList_DataBinding);
            container.Controls.Add(cbList);

            l = new Literal();
            l.Text = "<br>";
            container.Controls.Add(l);
        }

        void cbList_DataBinding(object sender, EventArgs e)
        {
            CheckBoxList cbList = (CheckBoxList)sender;
            RSParameter reportParam = ((DataListItem)cbList.NamingContainer).DataItem as RSParameter;

            cbList.Items.Clear();
            foreach (var param in reportParam.ValidValues.Values)
            {
                cbList.Items.Add(new ListItem(param.Label, param.Value));
            }

            if (reportParam.ValidValues.Count > 0)
            {
                List<string> selectedvalues = reportParam.GetValues();

                foreach (ListItem item in cbList.Items)
                {
                    if (selectedvalues.Contains(item.Value))
                    {
                        item.Selected = true;
                    }
                }
            }
            cbList.Visible = reportParam.ValidValues.Count > 0 && !reportParam.Connected && reportParam.MultipleValue;
        }

        void ddList_DataBinding(object sender, EventArgs e)
        {
            DropDownList ddList = (DropDownList)sender;
            RSParameter reportParam = ((DataListItem)ddList.NamingContainer).DataItem as RSParameter;

            ddList.DataSource = reportParam.ValidValues.Values;

            if (reportParam.ValidValues.Count > 0
                && reportParam.ValidValues.ContainsKey(reportParam.GetValue()))
            {
                ddList.SelectedValue = reportParam.GetValue();
            }
            ddList.Visible = reportParam.ValidValues.Count > 0 && !reportParam.Connected && !reportParam.MultipleValue;
        }

        void Name_DataBinding(object sender, EventArgs e)
        {
            Literal l = (Literal)sender;
            RSParameter reportParam = ((DataListItem)l.NamingContainer).DataItem as RSParameter;
            l.Text = reportParam.Name;
        }

        void Value_DataBinding(object sender, EventArgs e)
        {
            TextBox tb = (TextBox)sender;
            RSParameter reportParam = ((DataListItem)tb.NamingContainer).DataItem as RSParameter;
            tb.Text = reportParam.Connected ? "Connected" : reportParam.GetValue();
            tb.Enabled = !reportParam.Connected;
            tb.Visible = reportParam.ValidValues.Count == 0 || reportParam.Connected;
        }

        #endregion
    }
}
